package edu.ntu.im.p2ptrade.action.helper;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import edu.ntu.im.p2ptrade.OwnerManager;
import edu.ntu.im.p2ptrade.P2PTrade;
import edu.ntu.im.p2ptrade.entity.ItemRepository;

public class InitServlet extends HttpServlet {
	public static String configHome;

	public static Integer port;

	@Override
	public void init(ServletConfig config) throws ServletException {
		configHome = config.getInitParameter("configHome");
		port = Integer.parseInt(config.getInitParameter("jxtaPort"));
		File f = new File(configHome);
		if (!f.exists()) {
			f.mkdir();
		}
		
		try {
			OwnerManager.initOwner(configHome);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if (OwnerManager.established()) {
			try {
				P2PTrade.init(OwnerManager.getOwner().getName(), configHome,
						port);
				P2PTrade.getInstance();
			} catch (Exception e) {
				e.printStackTrace();
				System.exit(1);
			}
		}
		ItemRepository.initialize();
	}

}
